﻿using Jaeger;
using Jaeger.Reporters;
using Jaeger.Samplers;
using Jaeger.Senders.Thrift;
using JaegerDemo.Shared.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenTracing;
using OpenTracing.Util;

namespace JaegerDemo.Shared;

public static class TracingExtensions
{
    public static void AddJaegerTracer(this IServiceCollection services, JaegerOptions jaegerOptions, string serviceName)
    {
        services.AddSingleton<ITracer>(serviceProvider =>
        {
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            var sampler = new ConstSampler(sample: true);
            var reporter = new RemoteReporter.Builder()
                    .WithLoggerFactory(loggerFactory)
                    .WithSender(new UdpSender(jaegerOptions.Host, int.Parse(jaegerOptions.Port), 0))
                    .Build();

            var tracer = new Tracer.Builder(serviceName)
                .WithLoggerFactory(loggerFactory)
                .WithSampler(sampler)
                .WithReporter(reporter)
                .Build();

            GlobalTracer.Register(tracer);

            return tracer;
        });
    }
}